<template>
  <el-dialog :title="title" v-model="dialogVisible" width="700px" append-to-body destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="personnelName">
            <el-input v-model="form.personnelName" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="人员编码" prop="personnelCode">
            <el-input v-model="form.personnelCode" placeholder="请输入人员编码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属供应商" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%">
              <el-option
                v-for="item in supplierOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="级别" prop="level">
            <el-select v-model="form.level" placeholder="请选择级别" style="width: 100%">
              <el-option
                v-for="dict in levelOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="人月单价" prop="monthlyRate">
            <el-input-number
              v-model="form.monthlyRate"
              :min="0"
              :precision="2"
              :step="1000"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="form.idNumber" placeholder="请输入身份证号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
              <el-option
                v-for="dict in genderOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="form.birthDate"
              type="date"
              placeholder="请选择出生日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入电子邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入场日期" prop="entryDate">
            <el-date-picker
              v-model="form.entryDate"
              type="date"
              placeholder="请选择入场日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="离场日期" prop="leaveDate">
            <el-date-picker
              v-model="form.leaveDate"
              type="date"
              placeholder="请选择离场日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in statusOptions" :key="dict.value" :label="dict.value">{{
                dict.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, PropType, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { addPersonnel, updatePersonnel } from "@/api/attendance/personnel";
import {
  PersonnelVO,
  PersonnelForm,
  PersonnelStatus,
  PersonnelLevel,
  SupplierOption,
  Gender
} from "@/types/attendance/personnel";
import { handleFormError } from "@/utils/error-handler";

export default defineComponent({
  name: "PersonnelForm",
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: ""
    },
    personnel: {
      type: Object as PropType<PersonnelVO>,
      required: true
    },
    supplierOptions: {
      type: Array as PropType<SupplierOption[]>,
      required: true
    }
  },
  emits: ["update:modelValue", "success"],
  setup(props, { emit }) {
    // 性别选项
    const genderOptions = [
      { value: "0", label: "男" },
      { value: "1", label: "女" },
      { value: "2", label: "未知" }
    ];

    // 级别选项
    const levelOptions = [
      { value: "01", label: "初级" },
      { value: "02", label: "中级" },
      { value: "03", label: "高级" },
      { value: "04", label: "专家" }
    ];

    // 状态选项
    const statusOptions = [
      { value: "0", label: "在岗" },
      { value: "1", label: "离场" },
      { value: "2", label: "休假" }
    ];

    // 表单引用
    const formRef = ref<FormInstance>();
    const loading = ref(false);
    const dialogVisible = ref(props.modelValue);

    // 表单数据
    const form = reactive<PersonnelForm>({
      personnelName: "",
      personnelCode: "",
      idNumber: "",
      supplierId: "",
      gender: Gender.UNKNOWN,
      birthDate: "",
      level: PersonnelLevel.INTERMEDIATE,
      monthlyRate: 0,
      phoneNumber: "",
      email: "",
      entryDate: "",
      leaveDate: "",
      status: PersonnelStatus.ON_JOB,
      remark: ""
    });

    // 表单校验规则
    const rules = reactive<FormRules>({
      personnelName: [
        { required: true, message: "请输入姓名", trigger: "blur" },
        { min: 2, max: 50, message: "姓名长度在2到50个字符之间", trigger: "blur" }
      ],
      personnelCode: [
        { required: true, message: "请输入人员编码", trigger: "blur" },
        { min: 2, max: 30, message: "人员编码长度在2到30个字符之间", trigger: "blur" }
      ],
      idNumber: [
        { required: true, message: "请输入身份证号", trigger: "blur" },
        {
          pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
          message: "请输入正确的身份证号码",
          trigger: "blur"
        }
      ],
      supplierId: [{ required: true, message: "请选择所属供应商", trigger: "change" }],
      gender: [{ required: true, message: "请选择性别", trigger: "change" }],
      level: [{ required: true, message: "请选择级别", trigger: "change" }],
      monthlyRate: [{ required: true, message: "请输入人月单价", trigger: "blur" }],
      phoneNumber: [
        { required: true, message: "请输入手机号码", trigger: "blur" },
        {
          pattern: /^1[3-9]\d{9}$/,
          message: "请输入正确的手机号码",
          trigger: "blur"
        }
      ],
      email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
      entryDate: [{ required: true, message: "请选择入场日期", trigger: "change" }],
      status: [{ required: true, message: "请选择状态", trigger: "change" }]
    });

    // 重置表单
    const resetForm = () => {
      form.personnelName = "";
      form.personnelCode = "";
      form.idNumber = "";
      form.supplierId = "";
      form.gender = Gender.UNKNOWN;
      form.birthDate = "";
      form.level = PersonnelLevel.INTERMEDIATE;
      form.monthlyRate = 0;
      form.phoneNumber = "";
      form.email = "";
      form.entryDate = "";
      form.leaveDate = "";
      form.status = PersonnelStatus.ON_JOB;
      form.remark = "";

      // 延迟重置表单校验结果，确保DOM已更新
      setTimeout(() => {
        formRef.value?.clearValidate();
      }, 0);
    };

    // VO转Form
    const convertVOToForm = (vo: PersonnelVO): PersonnelForm => {
      return {
        personnelName: vo.personnelName,
        personnelCode: vo.personnelCode,
        idNumber: vo.idNumber,
        supplierId: vo.supplierId,
        gender: vo.gender as Gender,
        birthDate: vo.birthDate,
        level: vo.level as PersonnelLevel,
        monthlyRate: vo.monthlyRate,
        phoneNumber: vo.phoneNumber,
        email: vo.email,
        entryDate: vo.entryDate,
        leaveDate: vo.leaveDate,
        status: vo.status as PersonnelStatus,
        remark: vo.remark
      };
    };

    // 初始化表单
    const initForm = () => {
      // 重置表单
      resetForm();
      // 如果是编辑模式，则填充表单数据
      if (props.personnel) {
        const formData = convertVOToForm(props.personnel);
        Object.assign(form, formData);
      }
    };

    // 监听visible变化
    watch(
      () => props.modelValue,
      val => {
        console.log("组件接收到modelValue变化:", val);
        dialogVisible.value = val;
        if (val) {
          console.log("开始初始化表单数据");
          initForm();
          console.log("表单数据初始化完成");
        }
      },
      { immediate: true }
    );

    // 取消
    const handleCancel = () => {
      console.log("取消按钮被点击");
      emit("update:modelValue", false);
      resetForm();
    };

    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return;

      await formRef.value.validate(async valid => {
        if (!valid) return;

        try {
          loading.value = true;

          const submitData = {
            ...form,
            personnelId: props.personnel?.personnelId
          };

          if (props.personnel?.personnelId) {
            // 更新
            await updatePersonnel(submitData);
            ElMessage.success("修改成功");
          } else {
            // 新增
            await addPersonnel(submitData);
            ElMessage.success("新增成功");
          }
          emit("update:modelValue", false);
          emit("success");
        } catch (error) {
          handleFormError(error, "人员");
        } finally {
          loading.value = false;
        }
      });
    };

    // 监听personnel属性变化（新增）
    watch(
      () => props.personnel,
      () => {
        if (props.modelValue) {
          console.log("personnel changed, reinitializing form");
          initForm();
        }
      },
      { deep: true }
    );

    // 监听对话框内部状态变化
    watch(
      () => dialogVisible.value,
      val => {
        console.log("对话框内部状态变化:", val);
        if (val !== props.modelValue) {
          console.log("发送update:modelValue事件:", val);
          emit("update:modelValue", val);
        }
      }
    );

    return {
      formRef,
      form,
      rules,
      loading,
      dialogVisible,
      levelOptions,
      statusOptions,
      genderOptions,
      handleCancel,
      submitForm
    };
  }
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
